<?php
class file_system {
	/**
	 * Creates directory
	 *
	 * @param string $_dir
	 * @return bool
	 */
	public static function create_dir($_dir) {
		if (!is_dir($_dir)) return @mkdir($_dir, 0777);
		else return is_writable($_dir);
	}

	/**
	 * Removes directories tree
	 *
	 * @param string $path
	 * @return bool
	 */
	public static function remove_tree($path) {
		if (file_exists($path)){
			$h = @opendir($path);
			if ($h === false) return false;
			while (($file = readdir($h)) !== false) {
				if ($file != "." && $file != "..") {
					$curent_path = $path . "/" . $file;
					if (is_dir($curent_path)) {
						if (!self::remove_tree($curent_path)) return false;
						if (!@rmdir($curent_path)) return false;
					} else {
						if (!@unlink($curent_path)) return false;
					}
				}
			}
			closedir($h);
		}
		return true;
	}

	/**
	 * Removes directory
	 *
	 * @param string $dir
	 * @return bool
	 */
	function remove_dir($dir) {
		if (file_exists($dir)) {
			return @rmdir($dir);
		}
		return false;
	}

	/**
	 * Copies direcoties tree
	 * 
	 * @param string $source
	 * @param string $dest
	 * @return bool
	 */
	public static function copy_tree($source, $dest) {
		$h = opendir($source);
		if ($h === false) return false;
		while (($file = readdir($h)) !== false) {
			if ($file != "." && $file != "..") {
				$curent_path = $source . "/" . $file;
				$dest_path = $dest . "/" . $file;
				if (is_dir($curent_path)) {
					if (self::create_dir($dest_path)) return false;
					if (self::copy_tree($curent_path . "/", $dest_path . "/")) return false;
				} else {
					if (copy($curent_path, $dest_path) === false) return false;
					if (chmod($dest_path, 0777) === false) return false;
				}
			}
		}
		closedir($h);
		return true;
	}
}
?>